<!--
 * @Desc:拖拽上传图片
 * @author cheegon
 * @date 6/2/2021  3:00 PM
-->
<template>
  <el-dialog
      v-dialog-drag
      :title="uploadInfo.title"
      class="upload-box"
      :close-on-click-modal="false"
      :visible.sync="isShowPop"
      width="400px"
      center>
    <div style="position: relative;">
      <div class="vv " v-if="uploadInfo.fileType==='img'">
        <div contenteditable="" style="width: 100%;height: 100%;position: absolute;top:0;left: 0;z-index: 1"
             ref="contentRef"></div>
        <div
            style="pointer-events: none;background-color:#fff;width: 100%;height: 100%;text-align: center;line-height: 50px ;position: absolute;top:0;left: 0;z-index: 2">
          可将截图、网络图片或本地图片粘贴到此处
        </div>
      </div>
      <el-upload ref="upload"
                 drag
                 :multiple="uploadInfo.limit>1"
                 :http-request="handleUploadFile"
                 :on-remove="handleRemove"
                 :on-success="handleUploadSuccess"
                 :on-change="handleChange"
                 :on-error="handleError"
                 :before-upload="handleBeforeUpload"
                 :on-preview="handlePreview"
                 :file-list="fileList"
                 :disabled="disabled"
                 :show-file-list="isShowFileList"
                 :accept="uploadInfo.accept"
                 action="customize">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </el-upload>
      <div class="v_pic_list" v-if="uploadInfo.fileType==='img'">
        <div v-for="(item,index) in imageList" :key="index" class="v_pic_item">
          <el-image class="i_img" :src="item" alt=""
                    :preview-src-list="imageList">
          </el-image>
          <div class="v_cv v_cursor" @click="handleDelImage(item)">
            <i class="el-icon-close"></i>
          </div>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleComplete">确 定</el-button>
      </span>
  </el-dialog>
</template>
<script>

import dialogMixin from '@/mixins/dialogMixin'
import { reqUpload } from '@/api/uploadApi'
import { compressAccurately } from 'image-conversion'

const defInfo = () => {
  return {
    fileType: 'img',
    limit: 1,
    maxFileSize: 2,
    title: '图片上传',
    accept: 'image/jpeg,image/jpg,image/png',
    compress: true
  }
}
export default {
  name: 'DragUpload',
  props: {},
  mixins: [dialogMixin],
  data() {
    return {
      uploadInfo: defInfo(),
      loading: false,
      localFile: {},
      imageUrl: '',
      fileList: [],
      disabled: false,
      isShowFileList: false,
      imageList: [],
      uploadCount: 0
    }
  },
  created() {

  },
  methods: {
    refresh() {
      this.uploadInfo = Object.assign({}, defInfo(), this.info)
      console.log(this.uploadInfo)
      this.fileList = []
      this.imageList = []
      this.uploadCount = 0
      if (this.uploadInfo.fileType === 'img') {
        this.uploadInfo.accept = 'image/jpeg,image/jpg,image/png'
        this.isShowFileList = false
        document.addEventListener('paste', this.onPasteUpload)
      } else if (this.uploadInfo.fileType === 'excel') {
        this.uploadInfo.accept = 'application/vnd.ms-excel'
        this.isShowFileList = true
      } else if (this.uploadInfo.fileType === 'pdf') {
        this.uploadInfo.accept = 'application/pdf'
        this.isShowFileList = true
      }
    },
    emitInput(val) {
      this.$emit('input', val)
      if (val) {
        if (this.uploadInfo.limit == 1) {
          this.imageList = [val]
        } else {
          this.imageList.push(val)
        }
      }
    },
    handleRemove(file, fileList) {
      this.emitInput('')
    },
    handleChange(file) {
      console.log("sfsf")
      // let realFile = file.raw
      // if (this.fileType === 'img') {
      //   const isJPG = this.judgeImg(realFile.type)
      //   const isLt2M = realFile.size / 1024 / 1024 < 2
      //   if (!isJPG || !isLt2M) {
      //     return
      //   }
      // }
    },
    handleBeforeUpload(file) {
      if (this.uploadInfo.fileType === 'img') {
        const isJPG = this.judgeImg(file.type)
        const isNormalSize = file.size / 1024 / 1024 < this.uploadInfo.maxFileSize
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/PNG 格式!')
          return false
        }
        if (this.uploadInfo.compress) {
          return new Promise((resolve) => {
            if (isNormalSize) {
              resolve(file)
            } else {
              compressAccurately(file, 400).then(res => {
                resolve(res)
              })
            }
          })
        }else {
          if (!isNormalSize){
            this.$message.warning(`图片过大, 单张图片最大不能超过${this.uploadInfo.maxFileSize}M`)
            return false
          }
        }
      }
      return true
    },
    handlePreview(file) {

    },
    handleComplete() {
      this.isShowPop = false
      this.$emit("complete", this.imageList)
    },
    handleDelImage(item) {
      this.imageList = this.imageList.filter(it => {
        return item != it
      })
      this.uploadCount--
      this.$emit('onRemove', item)
    },
    handleError(file) {
      console.log(file)
      console.log('失败')
    },
    handleUploadFile(params) {
      let limit = this.uploadInfo.limit
      if (limit != 1 && this.uploadCount >= limit) {
        this.$message.warning(`最多只能上传${ limit }个文件!`)
        return
      }
      if (this.uploadInfo.fileType === 'img') {
        this.uploadCount++
        this.loading = true
        let file = params.file
        const form = new FormData()
        form.append('file', file)
        reqUpload(form).then(data => {
          this.emitInput(data.url)
          this.loading = false
        }).catch(() => {
          this.uploadCount--
          this.loading = false
        })
      }
    },
    handleUploadSuccess(res, file) {

    },
    onPasteUpload(event) {
      let items = event.clipboardData && event.clipboardData.items
      let files = []
      let showTip = false
      let limit = this.uploadInfo.limit
      if (items && items.length) {
        // 检索剪切板items
        for (let i = 0; i < items.length; i++) {
          if (items[i].type.indexOf('image') !== -1) {
            let file = items[i].getAsFile()
            if (limit == 1) {
              !files.length && files.push(file)
            } else {
              if (this.uploadCount >= limit) {
                showTip = true
              } else {
                this.uploadCount++
                files.push(file)
              }
            }
          }
        }
      }
      if (showTip) {
        this.$message.warning(`最多只能上传${ limit }个文件!!`)
      }
      if (files.length === 0) {
        this.$refs.contentRef.innerHTML = ''
        return
      }
      this.loading = true
      let length = files.length
      files.map(file => {
        const form = new FormData()
        form.append('file', file)
        reqUpload(form).then(data => {
          this.emitInput(data.url)
          this.$refs.contentRef.innerHTML = ''
          length--
          if (length <= 0) {
            this.loading = false
          }
        }).catch(() => {
          length--
          this.uploadCount--
          if (length <= 0) {
            this.loading = false
          }
        })
      })
    },
    /**
     * 判断是否是文件
     * @returns {boolean}
     */
    judgeExcel(type) {
      let flag = ['xls', 'xlsx'].includes(type)
      // let type = this.info.fileType || 'img'
      // if (!flag) {
      //   this.$message.error('只能上传excel文件!')
      // }
      return flag
    },
    /**
     * 判断是否是pdf
     * @param type
     * @returns {boolean}
     */
    judgePdf(type) {
      let flag = ['pdf'].includes(type)
      // if (!flag) {
      //   this.$message.error('只能上传Pdf文件!')
      // }
      return flag
    },
    /**
     * 判断是否是img
     * @param type
     * @returns {boolean}
     */
    judgeImg(type) {
      return type === 'image/jpeg' || type === 'image/jpg' || type === 'image/png'
    },
  }
}
</script>

<style lang="stylus">
.upload-demo {
  margin 0 auto
}

.vv {
  border 1px dashed #e4e4e4
  width 360px
  height 50px
  border-radius 5px
  margin-bottom 10px
  position relative
  top 0
  left 0

  &:hover {
    border 1px dashed #0CABFF
  }

  pre {
    width 0
    height 0
    overflow: auto;
  }

  img {
    width 0
    height 0
  }
}

.v_pic_list {
  width 100%
  display flex
  flex-direction row
  margin-top 10px

  .v_pic_item {
    margin-right 10px
    position relative
    border-radius 5px
    border 1px solid #e4e4e4
    width 52px
    height 52px

    .i_img {
      width 60px
      height 60px
      border-radius 5px
    }

    .v_cv {
      width 20px
      height 20px
      background: rgba(0, 0, 0, 0.4);
      border-radius: 0px 2px 0px 100px;
      position absolute
      top 0px
      right 0px
      transition opacity 0.3s
    }

    i {
      position absolute
      top 1px
      right 1px
      font-size: 14px
      color #FFF
      opacity 1
      transition opacity 0.3s
    }

    &:hover {
      .v_cv {
        opacity 1
      }
    }
  }

}
</style>
